package com.yema.mytestlibrary.mvpcontract

import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import java.lang.ref.Reference
import java.lang.ref.WeakReference


/**
 * <p>文件描述</p>
 * 用户名:yema
 * 时间:2019/6/25   10:32
 */
abstract class BasePresenter<V> {


    var mViewRef: Reference<V>? = null//View接口类型的弱引用

    //将所有正在处理的Subscription都添加到CompositeSubscription中。统一退出的时候注销观察
    private var mCompositeDisposable: CompositeDisposable? = null

    /**
     * presenter和view关联
     *
     * @param view
     */
    fun attachView(view: V) {
        mViewRef = WeakReference(view)//建立关系
    }

    fun addDisposable(disposable: Disposable) {
        if (mCompositeDisposable == null) {
            mCompositeDisposable = CompositeDisposable()
        }
        mCompositeDisposable!!.add(disposable)
    }

    /**
     * 清楚绑定观察者
     */
    fun clearDisposable() {
        if (mCompositeDisposable != null && !mCompositeDisposable!!.isDisposed) {
            mCompositeDisposable!!.clear()
        }
    }

    //在界面退出等需要解绑观察者的情况下调用此方法统一解绑，防止Rx造成的内存泄漏
    fun dispose() {
        if (mCompositeDisposable != null && !mCompositeDisposable!!.isDisposed) {
            mCompositeDisposable!!.dispose()
        }
    }

    protected fun getView(): V {
        return mViewRef!!.get()!!
    }

    /**
     * 判断presenter和view是否关联
     *
     * @return
     */
    fun isViewAttached(): Boolean {
        return mViewRef != null && mViewRef!!.get() != null
    }

    /**
     * presenter和view解除关联
     */
    fun detachView() {
        if (mViewRef != null) {
            mViewRef!!.clear()
            mViewRef = null
        }

        dispose()
    }
}